package com.qf.fmall2203.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2203.user.entity.Users;
import com.qf.fmall2203.user.service.IUsersService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    IUsersService usersService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        final String username = (String) token.getPrincipal();

        final Users dbuser = usersService.getOne(new QueryWrapper<Users>().eq("username", username));

        if (dbuser==null){
            throw new UnknownAccountException("用户名在数据库中不存在");
        }

        final String md5Password = dbuser.getPassword();
        final String salt = dbuser.getSalt();

        return new SimpleAuthenticationInfo(dbuser, md5Password, ByteSource.Util.bytes(salt), this.getName());

    }
}
